<?php

namespace app\controller;

use app\model\Game;
use app\model\Package;
use app\model\TokenInfo;
use app\queue\redis\in_page\InPush;
use app\queue\redis\push_page\PagePush;
use support\Cache;
use support\Db;
use support\Log;
use support\Redis;
use support\Request;

class Index
{
    public function index(Request $request)
    {
        return env('APP_URL','');

    }

    public function store(Request $request){
        $data = $request->get();
        return json($data);
    }

    protected function getCsvContent(){

    }

    public function evalCode(Request $request)
    {
        $all = $request->post();
        if($all){
            ob_start();
            $code = $request->input('code');
            $file = $request->file('file');
            $admin_id = 0;
            try{

                eval($code);
                $dump = ob_get_contents();
                //$Redis->set('test_evalCode',$code);
                Log::notice('evalCode:admin_id:'.$admin_id.':'.var_export($code,true));
            }catch (\Throwable $exception){
                return ($exception->getMessage());
            }
            return $dump.getServerIndex().'end';
        }
        return view('index/code', ['name' => 'webman']);
    }

    public function view(Request $request)
    {
        return view('index/view', ['name' => 'webman']);
    }
    public function push_html(Request $request)
    {
        $all = $request->post();

        $is_async = $all['is_async'] ?? 1;unset($all['is_async']);
        $request_id = requestId();
        if($all){
            $package_id = $all['package_id'];
            $Package = new Package();
            $os_id = $Package->where('id',$package_id)->value('plugin_type');
            ini_set('memory_limit', '-1');
            $in_limit = 10000;
            $TokenInfo = new TokenInfo();
            //推送参数
            $message = [];
            if(isset($all['custom_data'])){
                foreach ($all['custom_data'] as $key => $value){
                    if(in_array($key,['data','android_option','ios_option','android_notification','ios_notification'])){
                        $message['custom_data'][$key] = json_decode($value,true) ?: [];
                    }else{
                        $message['custom_data'][$key] = $value;
                    }
                }
                $message['notification'] = $all['notification'];
                $message['message_type'] = $all['message_type'];
                unset($all['custom_data'],$all['notification']);
            }


            $PublicPush = new \app\extensions\lib\push\Push();
            $InPush = new InPush();
            $is_dao  = false;
            $udids = [];
            $tokens = [];
            $search = $all['search'] ?? 0;


            /* @var $file \Webman\Http\UploadFile */
            $data = $request->file();
            $post_file_columns = ['udid_file','token_file'];//同时只支持一个
            foreach ($post_file_columns as $column){
                if($search) continue;
                if(!isset($data[$column])) continue;
                $file = $data[$column];
                if(!$file->isValid()) continue;
                $extension = $file->getUploadExtension();
                if($extension!='csv') return 'udid文件格式只能是csv';
                $tmp_file = $file->getRealPath();
                //内存限制
                $lists = array_filter(explode("\n",trim(str_replace("\r",'',file_get_contents($tmp_file)))));
                $sum = count($lists);
                $lists = array_chunk($lists,$in_limit);
                //内存限制则需要while(! feof($file)) $content = fgetcsv($file);

                $times = count($lists);
                $field = str_replace('_file','',$column);
                Log::channel('request')->info($request_id.':sum-count:'.$sum);
                $ikey = $request_id.'_'.InPush::$update_redis_queue_key;//存储key
                foreach ($lists as $k=> $list){
                    $list = array_filter($list);
                    $is_dao  = true;
                    Redis::lPush($ikey,implode(',',$list));//数据先放到指定缓存队列中,getUserList查询in时间久

                }
                if(!$is_dao){
                    return '表格数据为空';
                }
                $userData = ['package_id'=>$package_id,'os_id'=>$os_id];
                $info = "push_html:file:{$column}";
                \Webman\RedisQueue\Redis::send($InPush->queue,array_merge(['key'=>$ikey],
                    compact('field','userData','message','request_id','info')));//触发队列（添加队列数据

                return '分批推送,次数:'.$times.'--request_id:'.$request_id;
            }



            //搜索角色/区服
            //isset($all['package_id']) && $all['package_id'] = implode(',',$all['package_id']);
            $role_name = $all['role_name'] ?? '';
            $server_name = $all['server_name'] ?? '';
            $role_info = $role_name || $server_name;
            if(!$search && $role_info){

                $Package = new Package();
                $data = $Package->where('id',$package_id)->first();
                $cate_id = $data->cate_id;
                $raw = [];
                $role_name && $role_name = urlencode($role_name);
                $role_name && $raw[] = "(role_id = '{$role_name}' or role_name like '%{$role_name}%')";
                $server_name && $raw[] = "(server_id = '{$server_name}' or server_name = '{$server_name}')";

                if($raw){

                    $build = Db::connection('mysql_data')->table('roles_'.$cate_id)
                        ->whereRaw(implode(' and ',$raw))->orderBy('id','desc');
                    $sum = $build->count('udid');
                    Log::channel('request')->info($request_id.':sum-count:'.$sum);
                    $lists = $build->pluck('udid')->toArray();
                    $lists = array_chunk($lists,$in_limit);
                    $times = count($lists);
                    $ikey = $request_id.'_'.InPush::$update_redis_queue_key;//存储key
                    $field = 'udid';
                    foreach ($lists as $k=> $list){
                        Redis::lPush($ikey,implode(',',$list));//数据先放到指定缓存队列中,getUserList查询in时间久
                    }
                    $userData = ['package_id'=>$package_id];
                    \Webman\RedisQueue\Redis::send($InPush->queue,array_merge(['key'=>$ikey],
                        compact('field','userData','message','request_id')));//触发队列（添加队列数据

                    return '分批推送,次数:'.$times.'--request_id:'.$request_id;
                }
            }

            if($udids){
                $all['udid'] .= ','.implode(',',$udids);
            }
            if($tokens){
                $all['token'] .= ','.implode(',',$tokens);
            }
            $all['udid'] = trim($all['udid'],',');
            $all['token'] = trim($all['token'],',');
            if($search){
                $build = new TokenInfo();
                $build = $build->where('package_id',$all['package_id']);
                if(isset($cudids)){
                    $build->wherein('udid',$cudids);
                }else{
                    if($all['udid']){
                        $build = $build->wherein('udid',explode(',',$all['udid']));
                    }
                    if($all['token']){
                        $build = $build->wherein('token',explode(',',$all['token']));
                    }
                }

                $tokenss = $build->orderBy('updated_at','desc')->limit(10)->pluck('token')->toArray();
                return json_encode($tokenss);
            }

            if(!$is_async){
                if(!$all['udid'] && !$all['token'] && !$role_info){
                    return '无udid,token,角色信息条件（数量可能过多';
                }
            }

            $userList = $TokenInfo->getUserList($all);

            if(!$is_async) {
                foreach ($userList as $os_id => $items){
                    $item = current($items);
                    $tokens = $item['tokens'];
                    $count = count(explode(',',$tokens));
                    if($count>100){
                        return '同步推送方式,数量过大:'.$count;
                    }
                }
            }

            $info = "push_html:push:page:1";
            $result = $PublicPush->push($userList,$message,boolval($is_async),'',[],$info);
            $request_id = $result['request_id'] ?? '';
            Log::channel('request')->info($request_id.':'.json_encode($all));
            if($is_async){
                $page = 1;
                $page++;
                $userData = $all;
                $info = "push_html:async";
                $datas = compact('request_id','userData','message','page','info');
                $status = \Webman\RedisQueue\Redis::send(PagePush::$update_redis_queue_key,$datas,1);
                $result['status'] = $status;
            }


            return var_export($result,true);
        }
        $ids = array_keys(Package::getPackageConfig());
        $Game = new Game();
        $fields = ['p.game_id','p.id','p.name','p.appname'];
        $packageList = $Game->from($Game->getTable().' as g')->rightJoin('packages as p','p.game_id','g.id')
            ->wherein('p.id',$ids)
            ->select($fields)->get()->toArray();
        return view('index/test_push', ['packageList' => $packageList]);
    }

    public function json(Request $request)
    {
        return json(['code' => 0, 'msg' => 'ok']);
    }

}
